package com.jiazhong.example.project.bookstore.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.example.project.bookstore.commons.bean.Logistics;
import com.jiazhong.example.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.example.project.bookstore.commons.mapper.LogisticsMapper;
import com.jiazhong.example.project.bookstore.commons.util.JsonResult;
import com.jiazhong.example.project.bookstore.commons.util.ResultTool;
import com.jiazhong.example.project.bookstore.front.service.LogisticsService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class LogisticsServiceImpl extends ServiceImpl<LogisticsMapper, Logistics> implements LogisticsService {

    @Override
    public JsonResult findLogisticsByUserId(String token) {
        Claims claims = JwtConfig.parseJWT(token);
        String userId = claims.get("id").toString();
        QueryWrapper<Logistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByAsc("status");
        List<Logistics> list = list(queryWrapper);
        return ResultTool.success(list);
    }

    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveLogistics(Logistics logistics, String token) {
        Claims claims = JwtConfig.parseJWT(token);
        String userId = claims.get("id").toString();
        logistics.setUserId(userId);
        // 1.判断是否是第一次添加地址
        QueryWrapper<Logistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        long count = count(queryWrapper);
        if (count == 0) {
            // 1.1 如果是 该地址就是常用地址
            logistics.setStatus(1);
            save(logistics);
            return ResultTool.success("success");
        }
        // 1.2 如果不是
        Integer status = logistics.getStatus();
        if (status == 2) {
            // 1.2.1 该地址不是常用地址
            save(logistics);
            return ResultTool.success("success");
        }
        // 1.2.2 该地址是常用地址
        UpdateWrapper<Logistics> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", 2);
        updateWrapper.eq("user_id", userId);
        updateWrapper.eq("status", 1);
        update(updateWrapper);
        save(logistics);
        return ResultTool.success("success");
    }

}
